package com.mars.security.core.social.qq.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;

/**
 * 组装Service provider
 * 1、实现QQ接口,
 * 2、继承 AbstractOAuth2ApiBinding ，其中该继承类中的属性
 *    private final String accessToken; // 获取令牌，多实例对象
 *    private RestTemplate restTemplate; // 提供发送http请求的
 * 3、调用第三方qq的参考文档连接：http://wiki.connect.qq.com/get_user_info
 * @Author: Mars
 * @Date: 2018/8/27 17:24
 */
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ{

    private Logger logger = LoggerFactory.getLogger(getClass());

    // 与qq用户信息对接的url:openid
    private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";
    // 获取用户信息的
    private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";

    private String appId;
    private String openId;

    // 将字符串转换成相应的类
    private ObjectMapper objectMapper = new ObjectMapper();

    // 构造方法
    public QQImpl(String accessToken,String appId){
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
        this.appId  = appId;

        // 通过请求获取openid
        String url = String.format(URL_GET_OPENID,accessToken);
        String result = getRestTemplate().getForObject(url,String.class);

        // 截取client返回值中的openid
        logger.info("截取client返回值中的openid,{}",result);
        this.openId = StringUtils.substringBetween(result,"openid:","}");
    }

    /**
     * 第六步：
     * 发送请求获取用户信息
     * @return
     */
    @Override
    public QQUserInfo getUserInfo(){
        String url = String.format(URL_GET_USERINFO,appId,openId);
        //  发送请求
        String result = getRestTemplate().getForObject(url,String.class);
        logger.info(result);
        QQUserInfo userInfo = null;
        try {
            userInfo = objectMapper.readValue(result,QQUserInfo.class);
            userInfo.setOpenId(openId);
            return userInfo;
        } catch (IOException e) {
            throw new RuntimeException("获取用户信息失败",e);
        }
    }
}
